The FOR LOOP is very similar to a WHILE LOOP.
The difference being a little bit more code is contained in the loop.
The FOR LOOP can be a little more compact than a WHILE LOOP.
Here’s the logic:
for ( create a counter; conditional statement; increment the counter){
do this;
}
Let’s use our fluctuating bagel cost from above and write this out.
Oops - bagels just went up 10 cents!
<?php
$bagel_price = 2.25;
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";
for ( $counter = 1; $counter <= 20; $counter += 1) {
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $bagel_price * $counter;
echo "</td></tr>";
}
echo "</table>";
?>
Once again, the loop is highlighted in blue.
You’ll notice that the counter is defined inside the loop as opposed to a variable outside.
And..below, you’ll see the output.
0 Comments
|
David Rentson
If this free PHP and MYSQL Tutorial is helpful for you... Great! Archives
October 2008
Categories
All
|